package com.mars.module.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.mars.common.response.PageInfo;
import com.mars.framework.context.ContextUserInfoThreadHolder;
import com.mars.module.admin.entity.SysFood;
import com.mars.module.admin.mapper.SysFoodMapper;
import com.mars.module.admin.response.SysShopCarResponse;
import com.mars.module.system.entity.SysUser;
import com.mars.module.system.mapper.SysUserMapper;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import com.mars.module.admin.request.SysShopCarRequest;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import com.mars.module.admin.mapper.SysShopCarMapper;
import org.springframework.beans.BeanUtils;
import com.mars.module.admin.entity.SysShopCar;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.mars.module.admin.service.ISysShopCarService;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 购物车业务层处理
 *
 * @author mars
 * @date 2024-04-15
 */
@Slf4j
@Service
@AllArgsConstructor
public class SysShopCarServiceImpl implements ISysShopCarService {

    private final SysShopCarMapper baseMapper;
    private final SysUserMapper userMapper;
    private final SysFoodMapper productMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public SysShopCar add(SysShopCarRequest request) {
        SysShopCar entity = SysShopCar.builder().build();
        BeanUtils.copyProperties(request, entity);
        Long id = ContextUserInfoThreadHolder.get().getId();
        entity.setUserId(id);
        List<SysShopCar> shopCarList = baseMapper.selectList(new QueryWrapper<SysShopCar>().eq("user_id", id).eq("food_id", request.getFoodId()));
        if (!shopCarList.isEmpty()) {
            SysShopCar sysShopCar = shopCarList.stream().findFirst().orElse(null);
            if (sysShopCar != null) {
                entity.setFoodNum(entity.getFoodNum() + 1);
                baseMapper.updateById(entity);
            }
        } else {
            entity.setFoodNum(1);
            baseMapper.insert(entity);
        }
        return entity;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean delete(Long id) {
        return baseMapper.deleteById(id) > 0;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteBatch(List<Long> ids) {
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean update(SysShopCarRequest request) {
        SysShopCar entity = SysShopCar.builder().build();
        BeanUtils.copyProperties(request, entity);
        return baseMapper.updateById(entity) > 0;
    }

    @Override
    public SysShopCar getById(Long id) {
        return baseMapper.selectById(id);
    }

    @Override
    public SysShopCarResponse pageList(SysShopCarRequest request) {
        Page<SysShopCar> page = new Page<>(request.getPageNo(), request.getPageSize());
        LambdaQueryWrapper<SysShopCar> query = this.buildWrapper(request);
        IPage<SysShopCar> pageRecord = baseMapper.selectPage(page, query);
        List<SysShopCar> records = pageRecord.getRecords();
        List<SysShopCar> recordsNew = new ArrayList<>();
        for (SysShopCar shopCar : records) {
            SysUser user = userMapper.selectById(shopCar.getUserId());
            SysFood product = productMapper.selectById(shopCar.getFoodId());
            shopCar.setUserName(user == null ? "" : user.getUserName());
            shopCar.setFoodName(product == null ? "" : product.getName());
            shopCar.setHeat(product.getHeat() * shopCar.getFoodNum());
            shopCar.setPrice(product.getPrice().multiply(new BigDecimal(shopCar.getFoodNum())));
            recordsNew.add(shopCar);
        }
        recordsNew = recordsNew.stream().skip((request.getPageNo() - 1) * request.getPageSize()).limit(request.getPageSize()).collect(Collectors.toList());
        pageRecord.setRecords(recordsNew);
        int totalHeat = recordsNew.stream().mapToInt(SysShopCar::getHeat).sum();
        BigDecimal totalPrice = recordsNew.stream().map(SysShopCar::getPrice).reduce(BigDecimal.ZERO, BigDecimal::add);
        SysShopCarResponse response = new SysShopCarResponse();

        response.setCarList(recordsNew);
        response.setTotalPrice(totalPrice);
        response.setTotalHeat(totalHeat);
        return response;
    }


    @Override
    public List<SysShopCar> list(SysShopCarRequest request) {
        LambdaQueryWrapper<SysShopCar> query = this.buildWrapper(request);
        return baseMapper.selectList(query);
    }

    private LambdaQueryWrapper<SysShopCar> buildWrapper(SysShopCarRequest param) {
        LambdaQueryWrapper<SysShopCar> query = new LambdaQueryWrapper<>();
        if (param.getFoodNum() != null) {
            query.eq(SysShopCar::getFoodNum, param.getFoodNum());
        }
        return query;
    }

}
